﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using NPOI.HSSF.UserModel;
using ShopB2C.Entity;
using ShopB2C.Helper;
using ShopB2C.Interfaces;

namespace ShopB2C.Export
{

    /// <summary>
    /// 分类导入导出
    /// </summary>
    public class Classify
    {

        private const string _moduleKey = "Product";
        private const string _classifyResourceName = "ShopB2C.Export.Xls.Classify.xls";
        private static IClassify _classify;

        static Classify()
        {
            _classify = DataBaseExecuter.CreateClassByName<IClassify>("Classify");
        }
        /// <summary>
        /// 获取分类模板文件
        /// </summary>
        /// <returns>Stream</returns>
        public static Stream GetClassifyTemplateFileStream()
        {
            return Assembly.GetExecutingAssembly().GetManifestResourceStream(_classifyResourceName);
        }
        /// <summary>
        /// 导入分类操作
        /// </summary>
        /// <param name="fs">指定文件的 Stream</param>
        /// <returns>错误列表</returns>
        public static List<string> Import(Stream s)
        {
            List<string> errorList = new List<string>();
            /*
            HSSFWorkbook workBook = new HSSFWorkbook(s);
            HSSFSheet classifySheet = workBook.GetSheetAt(0);
            HSSFSheet propertySheet = workBook.GetSheetAt(1);
            HSSFSheet propertyValSheet = workBook.GetSheetAt(2);

            // 导入分类
            for (int i = 1; i <= classifySheet.LastRowNum; i++) {
                try {
                    HSSFRow row = classifySheet.GetRow(i);
                    string classifyName = row.GetCell(0).StringCellValue;
                    int sequences = (int)row.GetCell(1).NumericCellValue;
                    string parentClassifyName = row.GetCell(2) == null
                        ? string.Empty
                        : row.GetCell(2).StringCellValue;

                    _classify.ClassifyAppend(new ClassifyEntity() {
                        Title = classifyName,
                        Sequence = sequences,
                        ParentClassifyId = string.IsNullOrEmpty(parentClassifyName)
                            ? 0
                            : _classify.GetClassifyByName(parentClassifyName, _moduleKey).ClassifyId,
                        ModuleKey = _moduleKey
                    });
                }
                catch (Exception ex) {
                    errorList.Add(string.Format("分类 - {0}行 - {1}", i, ex.Message));
                }
            }
            // 导入分类特性
            List<ClassifyEntity> classifyList = _classify.GetClassifyByModuleKey(_moduleKey);
            for (int i = 1; i <= propertySheet.LastRowNum; i++) {
                try {
                    HSSFRow row = propertySheet.GetRow(i);
                    string propertyName = row.GetCell(0).StringCellValue;
                    int sequences = (int)row.GetCell(1).NumericCellValue;
                    bool isSearch = (int)row.GetCell(2).NumericCellValue == 1 ? true : false;
                    string classifyName = row.GetCell(3).StringCellValue;

                    _classify.PropertyAppend(new ClassifyPropertyEntity() {
                        ClassifyId = classifyList.First(p => { return p.Title == classifyName; }).ClassifyId,
                        IsSearch = isSearch,
                        Sequence = sequences,
                        Name = propertyName
                    });
                }
                catch (Exception ex) {
                    errorList.Add(string.Format("分类特性 - {0}行 - {1}", i, ex.Message));
                }
            }
            // 导入分类特性值
            for (int i = 1; i <= propertyValSheet.LastRowNum; i++) {
                try {
                    HSSFRow row = propertyValSheet.GetRow(i);
                    string propertyValName = row.GetCell(0).StringCellValue;
                    int sequences = (int)row.GetCell(1).NumericCellValue;
                    string propertyName = row.GetCell(2).StringCellValue;
                    string classifyName = row.GetCell(3).StringCellValue;

                    int pageCount;
                    _classify.PropertyValAppend(new ClassifyPropertyValEntity() {
                        PropertyId = _classify.GetPropertyByClassify(classifyList
                            .First(c => { return c.Title == classifyName; }).ClassifyId, int.MaxValue, 1, out pageCount)
                                .First(p => { return p.Name == propertyName; }).PropertyId,
                        Sequence = sequences,
                        Name = propertyName
                    });
                }
                catch (Exception ex) {
                    errorList.Add(string.Format("分类特性值 - {0}行 - {1}", i, ex.Message));
                }
            }

            workBook = null;
            classifySheet = null;
            propertySheet = null;
            propertyValSheet = null;
*/
            return errorList;
        }
        /// <summary>
        /// 导出分类操作
        /// </summary>
        /// <param name="errorList">错误列表</param>
        /// <param name="classifyId">生成的分类</param>
        /// <param name="types">生成的选项</param>
        /// <returns>文件存放路径</returns>
        public static string Export(List<string> errorList, int classifyId, string types)
        {
            string tempPath = string.Format(@"{0}\{1}.xls", Path.GetTempPath(), RandomHelper.RandomString(20));
            HSSFWorkbook workBook = new HSSFWorkbook(GetClassifyTemplateFileStream());
            /*
            HSSFSheet classifySheet = workBook.GetSheetAt(0);
            HSSFSheet propertySheet = workBook.GetSheetAt(1);
            HSSFSheet propertyValSheet = workBook.GetSheetAt(2);

            List<ClassifyEntity> classifyList = classifyId > 0
                ? _classify.GetClassifyAllChildByModuleKeyAndId(_moduleKey, classifyId)
                : _classify.GetClassifyByModuleKey(_moduleKey);
            if (classifyList.Count > 0)
            {
                int i = 1, ii = 1, iii = 1, pageCount;
                // 写分类
                foreach (ClassifyEntity ce in classifyList)
                {
                    try
                    {
                        HSSFRow row = classifySheet.CreateRow(i);
                        row.CreateCell(0).SetCellValue(ce.Title);
                        row.CreateCell(1).SetCellValue(ce.Sequence);
                        if (ce.ParentClassifyId > 0 && ce.ParentClassifyId != classifyId)
                        {
                            row.CreateCell(2).SetCellValue(
                                classifyList.First(c => { return c.ClassifyId == ce.ParentClassifyId; }).Title);
                        }
                        i++;
                    }
                    catch (Exception ex)
                    {
                        errorList.Add(string.Format("分类 - {0} - {1}", ce.Title, ex.Message));
                    }
                }
                // 写特性
                foreach (ClassifyEntity ce in classifyList)
                {
                    List<ClassifyPropertyEntity> propertyList =
                        _classify.GetPropertyByClassify(ce.ClassifyId, int.MaxValue, 1, out pageCount);
                    propertyList = propertyList ?? new List<ClassifyPropertyEntity>();
                    if (propertyList.Count > 0)
                    {
                        foreach (ClassifyPropertyEntity cpe in propertyList)
                        {
                            try
                            {
                                HSSFRow row = propertySheet.CreateRow(ii);
                                row.CreateCell(0).SetCellValue(cpe.Name);
                                row.CreateCell(1).SetCellValue(cpe.Sequence);
                                row.CreateCell(2).SetCellValue(cpe.IsSearch ? 1 : 0);
                                row.CreateCell(3).SetCellValue(ce.Title);
                                ii++;
                            }
                            catch (Exception ex)
                            {
                                errorList.Add(string.Format("分类特性 - {0} - {1}", cpe.Name, ex.Message));
                            }
                        }
                        // 写特性值
                        foreach (ClassifyPropertyEntity cpe in propertyList)
                        {
                            List<ClassifyPropertyValEntity> propertyValList =
                                _classify.GetPropertyValByProperty(cpe.PropertyId, int.MaxValue, 1, out pageCount);
                            propertyValList = propertyValList ?? new List<ClassifyPropertyValEntity>();
                            if (propertyValList.Count > 0)
                            {
                                foreach (ClassifyPropertyValEntity cpve in propertyValList)
                                {
                                    try
                                    {
                                        HSSFRow row = propertyValSheet.CreateRow(iii);
                                        row.CreateCell(0).SetCellValue(cpve.Name);
                                        row.CreateCell(1).SetCellValue(cpve.Sequence);
                                        row.CreateCell(2).SetCellValue(cpe.Name);
                                        row.CreateCell(3).SetCellValue(ce.Title);
                                        iii++;
                                    }
                                    catch (Exception ex)
                                    {
                                        errorList.Add(string.Format("分类特性值 - {0} - {1}", cpve.Name, ex.Message));
                                    }
                                }
                            }
                        }
                    }
                }
                workBook.ActiveSheetIndex = 0;
            }
            int reduce = 0;
            if (!types.Contains("0"))
            {
                workBook.RemoveSheetAt(0);
                reduce = 1;
            }
            if (!types.Contains("1"))
            {
                workBook.RemoveSheetAt(1 - reduce);
                reduce += 1;
            }
            if (!types.Contains("2"))
            {
                workBook.RemoveSheetAt(2 - reduce);
            }
            using (FileStream fs = new FileStream(tempPath, FileMode.Create))
            {
                workBook.Write(fs);
            }

            classifySheet = null;
            propertySheet = null;
            propertyValSheet = null;
            workBook = null;
            */
            return tempPath;
        }
    }

}